//
//  ProgressView.swift
//  CustomProgressIndicator
//
//  Created by liy on 2025/1/15.
//

import UIKit

class ProgressView: UIView {
  override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = UIColor(white: 0.5, alpha: 0)
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  private var _progressValue: CGFloat = 0

  func setProgressValue(newValue: CGFloat) {
    _progressValue = newValue
    setNeedsDisplay()
  }

  func getProgressValue() -> CGFloat {
    return _progressValue
  }

  override func draw(_ rect: CGRect) {
    let ct = UIGraphicsGetCurrentContext()
    let r = rect.width / 2.0
    let center = CGPoint(x: r, y: r)

    // MARK: - 1. 画背景圆

    ct?.addArc(center: center, radius: r, startAngle: 0, endAngle: .pi * 2, clockwise: false)
    ct?.setFillColor(UIColor(white: 0.9, alpha: 1).cgColor)
    ct?.fillPath()

    // MARK: - 2. 画扇形

    // 移动到圆心
    ct?.move(to: center)

    // 添加弧线
    ct?.addArc(center: center, radius: r, startAngle: 0, endAngle: .pi * 2 * _progressValue, clockwise: false)

    // 从结束角度的点绘制一条线回到圆心，闭合路径
    ct?.addLine(to: center)

    ct?.setFillColor(UIColor.blue.cgColor)
    ct?.fillPath()
  }
}
